import subprocess
import os
import datetime
import logging
import re



srcPath = os.getcwd()


"""

set logger

"""


# 第一步，创建一个logger
logger = logging.getLogger()
logger.setLevel(logging.INFO)    # Log等级总开关

# 第二步，创建一个handler，用于写入日志文件
# os.chdir("D:\E000-学习资料\E000-学习资料\gitee\play-ground")
# logName = os.path.splitext(os.path.basename(os.__file__))[0] + '.log'
logName = "automatic_git.log"
logFile = os.path.join(os.getcwd(), logName)
fh = logging.FileHandler(logFile, mode='a')
fh.setLevel(logging.DEBUG)   # 输出到file的log等级的开关

# 第三步，再创建一个handler，用于输出到控制台
ch = logging.StreamHandler()
ch.setLevel(logging.WARNING)   # 输出到console的log等级的开关
 
# 第四步，定义handler的输出格式
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
# formatter = logging.Formatter("%(asctime)s -%(pathname)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
fh.setFormatter(formatter)
ch.setFormatter(formatter)

# 第五步，logger对象添加handler
logger.addHandler(fh)
logger.addHandler(ch)
 
# logger.critical(__file__)


logger.warning("Satrt srcPath: " + srcPath)
os.chdir('..')
dirs = os.getcwd()
logger.warning("Satrt dirs: " + dirs)


"""

check logFile

"""


if logFile:
    pass
else:
    with open(logFile, mode="ab") as f:
        pass
# 如果 log文件大于20M， 删除
if os.path.getsize(logFile)/1024/1024 > 20:
    try:
        os.remove(logFile)
    except Exception as e:
        logger.error(e)
#         sys.exit()


"""

automatic_git

"""

for dir_ in os.listdir(dirs):
    if os.path.isdir(os.path.join(dirs,dir_)):
        if  r".git" in os.listdir(os.path.join(dirs, dir_)) or r".gitee" in os.listdir(os.path.join(dirs, dir_)):
        # if dir_ != ".ipynb_checkpoints":
            os.chdir(os.path.join(dirs, dir_))
            logger.info("当前目录: " + os.getcwd())
            # logger.info(__file__)

            logger.warning('git status')
            with subprocess.Popen(['git', 'status'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as p:
                for line in p.stdout.readlines():
                    logger.info(line)

            logger.warning('git pull')
            with subprocess.Popen(['git', 'pull'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as p:
                for line in p.stdout.readlines():
                    logger.info(line)
                    
            logger.warning('git add .')
            with subprocess.Popen(['git', 'add', '.'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as p:
                for line in p.stdout.readlines():
                    logger.info(line)

            logger.warning('git commit -m {} '.format(datetime.datetime.strftime(datetime.datetime.now(), '%Y/%m/%d %H:%M:%S')))
            with subprocess.Popen(['git', "commit", "-m",  datetime.datetime.strftime(datetime.datetime.now(), '%Y/%m/%d %H:%M:%S')], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as p:
                for line in p.stdout.readlines():
                    logger.info(line)

            logger.warning('git push')
            with subprocess.Popen(['git', 'push'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as p:
                for line in p.stdout.readlines():
                    logger.info(line)
        else:
            continue
    else:
        continue

os.chdir(dirs)
logger.info("End srcPath: " + srcPath)